package com.yili.oa.entity;

import com.yili.oa.models.Admin;
import com.yili.oa.service.LoginService;
import com.yili.oa.utils.Exception.AjaxException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class CuRouShiroRealm extends AuthorizingRealm {
    @Autowired
    LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用醋肉自定义授权");
        String userName = (String)principalCollection.getPrimaryPrincipal();
        //从数据库或者缓存中获取角色数据
        //Set<String> roles = getRolesByUserName(userName);
        //从数据库或者缓存中获取权限数据
        //Set<String> permissions = getPermissionsByUserName(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("approval");
        simpleAuthorizationInfo.addStringPermission("stockPermission");
        simpleAuthorizationInfo.addStringPermission("userPermission");
        //simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("调用Curou自定义REALM");

        // 将AuthenticationToken强转为AuthenticationToken对象
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        // 获得从表单传过来的用户名
        String username = upToken.getUsername();

        // 如果用户不存在，抛此异常
        Admin admin = loginService.getByAccount(username);
        if (admin.getState().equals("1")){
            throw new AjaxException("该用户已被禁用 请联系管理员");
        }
        if (admin==null) {
            throw new UnknownAccountException("无此用户名！");
        }else{
            return new SimpleAuthenticationInfo(username,admin.getPassword(),super.getName());
        }
    }
}
